import request from "../../axios";
import { useEffect, useState } from "react";
import { Input, Select, Space, Button, Table, Spin, message } from "antd";
import "./index.css";
import { useSelector } from "react-redux";
import haneleExport from "../../component/Export";

// 定义合同产品的类型
interface ContractProduct {
  productName: string;
  productModel: string;
  productSpecification: string;
  unitPrice: number | string;
  quantity: number;
  totalPrice: number | string;
  remarks: string;
}

interface ContractProduct {
  data?: Contract[];
  totalCount?: number | null;
}

// 定义合同的类型
interface Contract {
  id: number;
  code: string;
  name: string;
  contractType: string;
  status: string;
  products: ContractProduct[];
  contractTime: string;
  address: string;
  // 新增表格所需字段
  taskSubject: string;
  contractNumber: string;
  serviceType: string;
  projectNumber: string;
  serviceEngineer: string;
  engineerPhone: string;
  repairOrder: string;
  warrantyStartTime: string;
  warrantyEndTime: string;
  serviceContent: string;
  isCharged: string;
  relatedOrder: string;
}

// 定义服务类型和工单人员选项
const serviceTypes = [
  { value: "0", label: "全部" },
  { value: "售后巡查", label: "售后巡查" },
  { value: "设备升级", label: "设备升级" },
  { value: "设备安装", label: "设备安装" },
  { value: "退换机", label: "退换机" },
  { value: "客户支持", label: "客户支持" },
  { value: "设备维修", label: "设备维修" },
  { value: "使用培训", label: "使用培训" },
  { value: "项目支持", label: "项目支持" }
];

// 定义服务状态选项
const serviceStatuses = [
  { value: "0", label: "全部" },
  { value: "中止", label: "中止" },
  { value: "完成", label: "完成" },
  { value: "处理中", label: "处理中" },
  { value: "签到", label: "签到" },
  { value: "接单", label: "接单" },
  { value: "回访", label: "回访" },
];

const CustmerSerive: React.FC = () => {
  const counter = useSelector((state: any) => state.counter.data);
  const [allData, setAllData] = useState<ContractProduct>();
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [keyword, setKeyword] = useState<string>("");
  const [serviceType, setServiceType] = useState<string | number>("0");
  const [worker, setWorker] = useState<string | number>("0");
  const [serviceStatus, setServiceStatus] = useState<string | number>("0");
  const [loading, setLoading] = useState<boolean>(false);

  const handleExport = async () => {
    message.success("开始下载");
    try {
      const response = await request.get(
        "/route/api/exportTickets",
        {
          accessToken: "",
          enterpriseId: counter?.corpId,
          keyword: keyword,
          serviceType: serviceType === "0" ? null : serviceType,
          status: serviceStatus === "0" ? null : serviceStatus,
        },
        true
      );
      haneleExport(response, "工单信息");
    } catch (error) {
      message.error("请求失败");
    }
  };

  // 获取数据的函数
  const getInitData = async (
    keywords: string = keyword,
    type: string | number = serviceType,
    workerValue: string | number = worker,
    status: string | number = serviceStatus,
    page: number = currentPage
  ): Promise<void> => {
    setLoading(true);
    try {
      const { data } = await request.get("/route/api/tickets", {
        accessToken: "",
        enterpriseId: counter?.corpId,
        keyword: keywords,
        serviceType: type === "0" ? null : type,
        status: status === "0" ? null : status,
        pageNum: currentPage,
        pageSize: pageSize,
      });
      setAllData(data);
    } catch (error) {
      message.error("请求失败");
      console.error("获取数据时出错:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleTableChange = (current: any, pageSize: any) => {
    setCurrentPage(current);
    setPageSize(pageSize);
  };

  // 重置的函数
  const onReset = async (): Promise<void> => {
    setKeyword("");
    setServiceType("0");
    setWorker("0");
    setServiceStatus("0");
    setCurrentPage(1);
    await getInitData("", "0", "0", "0", 1);
  };

  useEffect(() => {
    getInitData();
  }, [currentPage, pageSize]);

  const columns: any[] = [
    {
      title: "任务主题",
      dataIndex: "taskSubject",
    },
    {
      title: "单号",
      dataIndex: "orderNumber",
    },
    {
      title: "类型",
      dataIndex: "serviceType",
    },
    {
      title: "项目编号",
      dataIndex: "projectNumber",
    },
    {
      title: "服务工程师",
      dataIndex: "serviceEngineer",
    },
    {
      title: "工程师电话",
      dataIndex: "engineerPhone",
    },
    {
      title: "报修单",
      dataIndex: "repairOrder",
    },
    {
      title: "质保时间",
      render: (_: any, record: Contract) => {
        return `${record.warrantyStartTime} 至 ${record.warrantyEndTime}`;
      },
    },
    {
      title: "服务内容",
      dataIndex: "serviceContent",
    },
    {
      title: "是否收费",
      dataIndex: "isCharged",
    },
    {
      title: "相关工单",
      dataIndex: "relatedOrder",
    },
    {
      title: "状态",
      dataIndex: "status",
    },
  ];

  return (
    <div className="container">
      <Spin tip="数据加载中" spinning={loading}>
        <div className="search-container">
          <div className="search-filters">
            <Space direction="vertical" className="filter-group">
              <span className="filter-label">关键词</span>
              <Input
                className="filter-input"
                value={keyword}
                onChange={(e) => setKeyword(e.target.value)}
                placeholder="单号、项目编号、报修单、服务内容"
              />
            </Space>
            <Space direction="vertical" className="filter-group">
              <span className="filter-label">服务类型</span>
              <Select
                showSearch
                className="filter-select"
                value={serviceType}
                placeholder="请选择服务类型"
                onChange={(val) => setServiceType(val)}
              >
                {serviceTypes.map((option) => (
                  <Select.Option key={option.value} value={option.value}>
                    {option.label}
                  </Select.Option>
                ))}
              </Select>
            </Space>
            <Space direction="vertical" className="filter-group">
              <span className="filter-label">服务状态</span>
              <Select
                showSearch
                className="filter-select"
                value={serviceStatus}
                placeholder="请选择服务状态"
                onChange={(val) => setServiceStatus(val)}
              >
                {serviceStatuses.map((option) => (
                  <Select.Option key={option.value} value={option.value}>
                    {option.label}
                  </Select.Option>
                ))}
              </Select>
            </Space>
          </div>
          <div className="search-buttons">
            <Button
              key="search"
              className="search-button"
              onClick={() => {
                setCurrentPage(1);
                getInitData(undefined, undefined, undefined, undefined, 1);
              }}
            >
              查询
            </Button>
            <Button key="reset" className="reset-button" onClick={onReset}>
              重置
            </Button>
            <Button
              key="export"
              className="export-button"
              onClick={() => handleExport()}
            >
              导出Excel
            </Button>
          </div>
        </div>
        <div className="table-container">
          <Table
            columns={columns}
            className="device-log-table"
            dataSource={allData?.data}
            pagination={{
              showSizeChanger: true,
              pageSizeOptions: ["5", "10", "20"],
              total: allData?.totalCount || 0,
              current: currentPage,
              pageSize: pageSize,
              onChange: handleTableChange,
            }}
            scroll={{ x: 1800 }}
          />
        </div>
      </Spin>
    </div>
  );
};

export default CustmerSerive;
